<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{

    public function onBootstrap(MvcEvent $e)
    {
        $eventManager = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
        
        // Attach listener for unchecked exception logging
        $sharedManager = $e->getApplication()->getEventManager()->getSharedManager();
        $serviceManager = $e->getApplication()->getServiceManager();
        
        // Error logging
        $sharedManager->attach('Zend\Mvc\Application', 'dispatch.error', function ($event) use($serviceManager)
        {
            $exception = $event->getResult()->exception;
            
            if ($exception) {
                $serviceManager = $event->getApplication()->getServiceManager();
                
                $service = $serviceManager->get('Application\Service\ErrorHandling');
                $service->logException($exception);
            }
        });

        // Specify per-module layouts. Configuration is in module.config of the Application module
        $sharedManager->attach('Zend\Mvc\Controller\AbstractController', 'dispatch', function($e) {
        	$controller      = $e->getTarget();
        	$controllerClass = get_class($controller);
        	$moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
        	$config          = $e->getApplication()->getServiceManager()->get('config');

        	if (isset($config['module_layouts'][$moduleNamespace]))
        		$controller->layout($config['module_layouts'][$moduleNamespace]);
        }, 100);
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__
                )
            )
        );
    }
}
